package com.powernode.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.powernode.constant.BusinessEnum;
import com.powernode.domain.SysUser;
import com.powernode.dto.PasswordDto;
import com.powernode.model.Result;
import com.powernode.service.SysUserService;
import com.powernode.util.AuthUtil;
import com.powernode.vo.SysUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description:
 * @Author: Tong Ziyu
 * @Date: 2025/1/4 23:47
 */
@Slf4j
@RestController
@RequestMapping("sys/user")
@Api(tags = "用户信息接口管理")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("获取用户id和用户名")
    @GetMapping("info")
    public Result<SysUserVo> getUserInfo(){

        Long loginUserId = AuthUtil.getLoginUserId();
        SysUser one = sysUserService.lambdaQuery().eq(SysUser::getUserId, loginUserId).one();

        if (one != null) {
            SysUserVo sysUserVo = new SysUserVo();
            sysUserVo.setUsername(one.getUsername());
            sysUserVo.setUserId(one.getUserId());
            return Result.success(sysUserVo);
        }else{
            return Result.fail(BusinessEnum.UN_AUTHORIZATION);
        }
    }

    /**
     * 修改密码
     */
    @ApiOperation("修改密码")
    @PutMapping("password")
    public Result<String> updatePassword(@RequestBody PasswordDto passwordDto){
        log.info("修改密码-> 旧密码:{},新密码:{}",passwordDto.getPassword(),passwordDto.getNewPassword());
        Boolean b = sysUserService.updatePassword(passwordDto);
        return Result.handle(b);
    }


    /**
     * 开启方法前置权限校验
     *  第一步: 在security配置类上添加 @EnableGlobalMethodSecurity(prePostEnable=true)
     *  第二步: 在具体方法上添加@PreAuthorize() 注解
     *
     *  多条件分页查询系统管理员
     * @param
     * @return
     */
    @ApiOperation("多条件分页查询系统管理员")
    @GetMapping("page")
    @PreAuthorize("hasAuthority('sys:user:page')")
    public Result<Page> loadPage(@RequestParam(value = "current") Long current,
                                 @RequestParam(value = "size") Long size,
                                 @RequestParam(required = false) String username
                                 ){

        /*
            like(boolean condition, R column, Object val) 方法:
                - condition: 是否开启模糊查询,如果为true才开模糊查询
                - column: 查询字段
                - val: 查询值
         */

        // 注意这里创建 Page 对象后,最后查询出来的结果 也要赋值到这个对象里
        Page<SysUser> page = new Page<>(current, size);

        page = sysUserService.page(page,
                new LambdaQueryWrapper<SysUser>()
                        .like(StringUtils.hasText(username), SysUser::getUsername, username)
                        .orderByDesc(SysUser::getCreateTime));


        return Result.success(page);
    }

    /**
     * 新增管理员
     * @return
     */
    @ApiOperation("新增管理员")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result<String> saveSysUser(@RequestBody SysUser sysUser){
        /*
        新增对象流程:
            1. 首先用户名是否存在,如果存在则提示用户名已存在
            2. 如果用户名不存在,则保存用户信息
            3. 保存用户信息成功后,再保存用户角色信息
         */
        Integer count = sysUserService.saveUser(sysUser);

        return Result.handle(count > 0);
    }

    /**
     * 根据id查询用户
     * @param userId
     * @return
     */
    @ApiOperation("根据id查询用户")
    @GetMapping("info/{userId}")
    @PreAuthorize("hasAuthority('sys:user:info')")
    public Result<SysUser> loadUserById(@PathVariable("userId") Integer userId){
        SysUser sysUser = sysUserService.querySysUserById(userId);
        return Result.success(sysUser);
    }


    /**
     * 修改用户信息
     * @return
     */
    @ApiOperation("修改用户信息")
    @PutMapping()
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result<String> updateSysUser(@RequestBody SysUser sysUser){
        log.info("修改用户信息:{}",sysUser);
        Integer i = sysUserService.updateSysUser(sysUser);

        return Result.handle(i > 0);
    }

    /**
     * 删除用户信息[带批量]
     */
    @ApiOperation("xxx")
    @DeleteMapping("{ids}")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result<String> deleteBatchSysUserById(@PathVariable("ids") List<Long> ids){
        Integer count = sysUserService.removeBatchOrOne(ids);
        return Result.handle(ids.size() == count);
    }

}
